package cn.cutie.clot.mq.demo;

import cn.cutie.clot.mq.client.ClotBroker;
import cn.cutie.clot.mq.client.ClotConsumer;
import cn.cutie.clot.mq.client.ClotProducer;
import cn.cutie.clot.mq.model.ClotMessage;
import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;

/**
 * @Description:
 * @Author: Cutie
 * @CreateDate: 2024/6/27 20:30
 * @Version: 0.0.1
 */
public class ClotMqDemo {
    @SneakyThrows
    public static void main(String[] args) {
        long ids = 0;
//        String topic = "clot.order";
        String topic = "cn.cutie.test";
        ClotBroker broker = ClotBroker.getDefault();
        ClotProducer producer = broker.createProducer();

        ClotConsumer<?> consumer = broker.createConsumer(topic);
//        consumer.sub(topic);
        // 推模式
//        consumer.listen(topic, message -> {
//            // 这里处理消息，如果抛出异常 cn.cutie.clot.mq.client.ClotBroker.init 就不会ack
//            System.out.println("onMessage: " + message);
//        });

        ClotConsumer<?> consumer1 = broker.createConsumer(topic);
        consumer1.sub(topic);

        for (int i = 0; i < 10; i++) {
            Order order = new Order(ids, "order" + ids, 100.0 * ids);
            producer.send(topic, new ClotMessage<>(ids++, JSON.toJSONString(order), null));
        }

        // 拉模式
        for (int i = 0; i < 10; i++) {
            ClotMessage<String> message = (ClotMessage<String>) consumer1.recv(topic);
            System.out.println(message);
            consumer1.ack(topic, message);
        }
        while (true){
            char c = (char)System.in.read();
            if (c == 'q' || c == 'e'){
                consumer1.unsub(topic);
                break;
            }
            if (c == 'p') {
                Order order = new Order(ids, "order" + ids, 100.0 * ids);
                producer.send(topic, new ClotMessage<>(ids++, JSON.toJSONString(order), null));
                System.out.println("send ok: " + order);
            }
            if (c == 'c'){
                // 拉模式
                ClotMessage<String> message = (ClotMessage<String>) consumer1.recv(topic);
                System.out.println(message);
                System.out.println("poll ok: " + message);
                consumer1.ack(topic, message);
            }
            if (c == 'a'){
                for (int i = 0; i < 10; i++) {
                    Order order = new Order(ids, "order" + ids, 100.0 * ids);
                    producer.send(topic, new ClotMessage<>(ids++, JSON.toJSONString(order), null));
                    System.out.println("send ok 10 : " + order);
                }
            }
        }
    }
}
